const { mkdirSync } = require('fs');
const { resolve } = require('path');
const { sync } = require('glob');
const { createCoverageMap } = require('istanbul-lib-coverage');
const { createContext } = require('istanbul-lib-report');
const { create } = require('istanbul-reports');

const coverageMap = createCoverageMap();

const tmpDir = resolve(__dirname, '../../qa/tmp');
const outputDir = resolve(__dirname, '../../coverage-e2e-frontend');

const e2eCoverageFiles = sync(`${tmpDir}/js-istanbul-coverage-*.json`);

console.log(`Found ${e2eCoverageFiles.length} E2E coverage files`);

mkdirSync(outputDir, { recursive: true });

if (e2eCoverageFiles.length === 0) {
  console.warn('Warning: No E2E coverage files found.');
  console.warn('This could mean:');
  console.warn('  - E2E tests did not run');
  console.warn('  - BABEL_ENV=istanbul was not set during E2E test execution');
  console.warn('  - Tests did not exercise any frontend code');
  console.warn('  - Coverage collection failed during test execution');
  console.warn('Exiting without generating coverage report.');
  process.exit(0);
}

// Normalize coverage report generated by jest that has additional "data" key
// https://github.com/facebook/jest/issues/2418#issuecomment-423806659
const normalizeReport = (report) => {
  const normalizedReport = { ...report };
  Object.entries(normalizedReport).forEach(([k, v]) => {
    if (v.data) normalizedReport[k] = v.data;
  });
  return normalizedReport;
};

e2eCoverageFiles
  .map((coverageFile) => {
    console.log(`Processing: ${coverageFile}`);
    // eslint-disable-next-line global-require, import/no-dynamic-require
    return require(coverageFile);
  })
  .forEach((coverage) => {
    // E2E coverage is keyed by test location, extract coverage data values
    Object.values(coverage).forEach((report) => {
      coverageMap.merge(normalizeReport(report));
    });
  });

const context = createContext({ coverageMap, dir: outputDir });

['json', 'lcov', 'text-summary', 'clover', 'cobertura'].forEach((reporter) => {
  create(reporter, {}).execute(context);
});

console.log(`E2E coverage reports generated in ${outputDir}`);
